import { getCurrentInstance, type ComponentInstance } from "vue";
import YTable from "./Table.vue";
import type { State } from "./types";

type YTableInstance = InstanceType<typeof YTable> & {
  ctx: { $refs: { [ref: string]: YTableInstance } };
};

// ref名称前缀
export const TABLE_REF = "y-table";

export function useTable() {
  const $this = getCurrentInstance() as YTableInstance | null;

  const getTableRef = (index: number) => {
    const refName = TABLE_REF + index;
    return $this?.ctx?.$refs[refName];
  };

  // 根据index获取YTable的data
  const getTableData = (index: number) => {
    const $this = getTableRef(index);
    return $this && $this.getData();
  };

  // 根据index设置YTable的data
  const addTableData = (index: number) => {
    const $this = getTableRef(index);
    return $this && $this.addData();
  };

  const setTableState = (index: number, state: State) => {
    const $this = getTableRef(index);
    $this && $this.setState(state);
  };

  // 根据index设置ref名称 ：ytableref0，ytableref1 ...
  const tableRef = (index: number) => {
    return TABLE_REF + index;
  };

  return {
    getTableData,
    addTableData,
    getTableRef,
    setTableState,
    tableRef,
  };
}
